using System;
using com.yoozoo.gta.Extension;
using UnityEngine;
using UnityEngine.UI;
using WorldMapBase;
using Yoozoo.UI;

public class WorldPosUpdater : MonoBehaviour
{
    public Text coordText;

    private RectTransform mineCanvas;
    private UnityEngine.Camera uiCamera;

    private int lastArrowX = -1;
    private int lastArrowY = -1;

    private int m_serverId = 2000;// 服务器id
    private string m_strFormat = "";// 提示语多语言

    public void Init()
    {
        WorldCameraManager.AddLuaMoveEventHandler(UpdateWorldPos);
        mineCanvas = GameObject.Find("RootCanvas").GetComponent<RectTransform>();

        if (mineCanvas && mineCanvas.parent)
        {
            var uiCameraTrans = mineCanvas.parent.Find("UICamera");
            if (uiCameraTrans)
            {
                uiCamera = uiCameraTrans.GetComponent<UnityEngine.Camera>();
            }
        }
    }

    public void UnInit()
    {
        WorldCameraManager.RemoveLuaMoveEventHandler(UpdateWorldPos);
    }
    
    public void SetShowText(string strFormat)
    {
        m_strFormat = strFormat;
    }

    public void SetServerId(int serverId)
    {
        m_serverId = serverId;
        UpdateWorldPos(new Vector2(lastArrowX,lastArrowY));
    }

    public void UpdateWorldPos(Vector2 cameraCenterPos)
    {
        if (!mineCanvas || !uiCamera)
        {
            UnityEngine.Debug.LogError("找不到对应组件");
            return;
        }
        int iX = Mathf.FloorToInt(cameraCenterPos.x);
        int iY = Mathf.FloorToInt(cameraCenterPos.y);

        var data = WorldMapConfigData.GetMapData();
        if (data == null)
        {
            return;
        }
        int mapSize = WorldMapConfigData.GetMapData().mapWidth;
        iX = Mathf.Clamp(iX, 0, mapSize);
        iY = Mathf.Clamp(iY, 0, mapSize);
        if (iX!=lastArrowX || iY!=lastArrowY)
        {
            if (coordText.Valid())
            {
                coordText.text = string.Format(m_strFormat, m_serverId, iX, iY);
            }
            lastArrowX = iX;
            lastArrowY = iY;
        }
    }
}
